package codingforgreat.class46;

import java.util.HashMap;

public class Class01_Lc391 {
    public static boolean isRectangleCover(int[][] rectangles) {
        int l = Integer.MAX_VALUE;
        int r = Integer.MIN_VALUE;
        int u = Integer.MIN_VALUE;
        int d = Integer.MAX_VALUE;
        HashMap<String,Integer> map = new HashMap<>();
        int area = 0;
        for(int[] squ : rectangles){
            String le = squ[0] + "_" + squ[1];
            String ri = squ[2] + "_" + squ[3];
            map.put(le,map.getOrDefault(le,0) + 1);
            map.put(ri,map.getOrDefault(ri,0) + 1);
            area += (squ[2] - squ[0]) * (squ[3] - squ[1]);
            l = Math.min(squ[0], l);
            d = Math.min(squ[1], d);
            r = Math.max(squ[2], r);
            u = Math.max(squ[3], u);
        }
        if(area != (r - l) * (u - d)){
            return false;
        }
        if (
                map.getOrDefault(r + "_" + u,0) != 1
                        || map.getOrDefault(l + "_" + d, 0) != 1) {return false;}
        map.remove(r + "_" + u);
        map.remove(l + "_" + d);
        for(String key : map.keySet()){
            int value = map.get(key);
            if((value & 1) != 0){
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        int[][] ma = new int[][]{{1,1,3,3},{3,1,4,2},{3,2,4,4},{1,3,2,4},{2,3,3,4}};
        System.out.println(isRectangleCover(ma));
    }
}
